/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hxg.portmgr.core.task;

import hxg.portmgr.core.device.Device;
import hxg.portmgr.core.device.intf.Intf;
import hxg.portmgr.core.oper.OperType;
import hxg.portmgr.core.oper.snmp.SnmpOper;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author hxg
 */
public class ScanIntfTask {
    
    final static Map<Device, Thread> scanIntf_tasks = new ConcurrentHashMap<>();
    
    public static void ScanIntf(final Collection<Device> devs) {
        for (final Device dev : devs) {
            ScanIntf(dev);
        }
    }
    
    public static void ScanIntf(final Device dev) {
        if (!scanIntf_tasks.containsKey(dev)) {
            Thread t = new Thread() {
                @Override
                public void run() {
                    try {
                        Intf[] ifs = ((SnmpOper)dev.getOper(OperType.SnmpOper)).scanIntfs();
                        dev.saveIntfs(ifs);
                        Logger.getLogger(ScanIntfTask.class.getName()).log(Level.INFO, "接口扫描任务[{0}]完成,扫描出个{1}端口", new Object[]{dev.getChsName(), ifs.length});
                        if (scanIntf_tasks.containsKey(dev)) {
                            scanIntf_tasks.remove(dev);
                            Logger.getLogger(ScanIntfTask.class.getName()).log(Level.INFO, "清除已完成的任务[{0}]", dev.getChsName());
                        }
                    } catch (IOException ex) {
                        Logger.getLogger(ScanIntfTask.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            };
            scanIntf_tasks.put(dev, t);
            t.start();
            Logger.getLogger(ScanIntfTask.class.getName()).log(Level.INFO, "添加并启动一条接口扫描任务[{0}]", dev.getChsName());
        }
        
    }
}
